<template>
  <div class="white-list feature-out">
    <div class="filter-container" ref="searchDiv">
      <el-input
        v-model="tableQuery.name"
        clearable
        style="width: 200px;"
        placeholder="请输入姓名"
        size="small"
        class="filter-item"
      ></el-input>

      <el-input
        v-model="tableQuery.certNo"
        clearable
        style="width: 200px;"
        placeholder="请输入身份证"
        size="small"
        class="filter-item"
      ></el-input>

      <el-input
        v-model="tableQuery.phone"
        clearable
        style="width: 200px;"
        placeholder="请输入手机号"
        size="small"
        class="filter-item"
      ></el-input>

      <el-select
        size="small"
        v-model="tableQuery.status"
        clearable
        placeholder="请选择状态"
        class="filter-item"
        style="width: 200px;"
      >
        <el-option
          v-for="(item, key) in statusArr"
          :key="key"
          :label="item"
          :value="key"
        ></el-option>
      </el-select>

      <el-select
        size="small"
        v-model="tableQuery.typeId"
        clearable
        placeholder="请选择名单类型"
        class="filter-item"
        style="width: 200px;"
      >
        <el-option
          v-for="(item, key) in typeId"
          :key="key"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>

      <el-button
        size="small"
        @click="handleFilter"
        type="primary"
        class="filter-item"
        ref="btnQuery"
      >
        查询
      </el-button>
      <el-button
        @click="handleReset"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
      >
        重置
      </el-button>
      <el-button
        @click="handlePop('add')"
        size="small"
        type="primary"
        class="filter-item"
        ref="btnRefresh"
      >
        添加用户
      </el-button>
      <el-button
        size="small"
        type="primary"
        class="filter-item"
        @click="rosterUpload('true')"
      >
        名单导入
      </el-button>
    </div>

    <el-table
      :data="tableData"
      :max-height="tableHeight"
      style="width: 100%;margin-bottom: 12px;"
      @sort-change="sortChange"
    >
      <el-table-column label="姓名" prop="name" align="center">
        <template slot-scope="scope">
          {{ nameEncryption(scope.row.name) }}
        </template>
      </el-table-column>
      <el-table-column
        label="身份证"
        prop="certNo"
        align="center"
        min-width="160px"
      >
        <template slot-scope="scope">
          {{
            scope.row.certNo.substring(0, 6) +
              '********' +
              scope.row.certNo.substring(
                scope.row.certNo.length - 4,
                scope.row.certNo.length
              )
          }}
          <!-- {{
            scope.row.certNo.length > 15
              ? scope.row.certNo.replace(/(\d{6})\d*(\d{4})/, '$1******$2')
              : scope.row.certNo.replace(/(\d{6})\d{6}(\d{3})/, '$1******$2')
          }} -->
        </template>
      </el-table-column>
      <el-table-column
        label="手机号"
        prop="phone"
        align="center"
        min-width="130px"
      >
        <template slot-scope="scope">
          {{ scope.row.phone.replace(/(\d{3})\d*(\d{4})/, '$1****$2') }}
        </template>
      </el-table-column>
      <el-table-column label="名单类型" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.type ? scope.row.type.name : '' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '有效' : '无效' }}
        </template>
      </el-table-column>
      <el-table-column label="名单有效期" align="center" min-width="180px">
        <template slot-scope="scope">
          {{ scope.row.validDateStart }} 至 {{ scope.row.validDateEnd }}
        </template>
      </el-table-column>
      <el-table-column
        label="剩余有效天数"
        prop="validDay"
        align="center"
        width="120px"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createdAt"
        align="center"
        width="160px"
        sortable="custom"
      >
      </el-table-column>
      <el-table-column
        label="更新时间"
        prop="updatedAt"
        align="center"
        min-width="180px"
        sortable="custom"
      >
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="100px">
        <template slot-scope="scope">
          <!-- <el-button type="text" size="mini" @click="handleDelete(scope.row.id)"
            >删除</el-button
          > -->
          <el-button
            type="text"
            size="mini"
            @click="handlePop('update', scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="tableQuery.page"
        :page-sizes="[10, 20, 50]"
        :page-size="tableQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 新增/编辑弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      class="new-dialog"
      width="500px"
    >
      <el-form
        class="small-space"
        label-position="right"
        label-width="80px"
        :model="createdItem"
        :rules="rules"
        ref="featureForm"
      >
        <el-form-item prop="name" label="姓名">
          <el-input
            size="small"
            type="text"
            :disabled="actionType === 'update'"
            v-model="createdItem.name"
            placeholder="请输入姓名"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="certNo" label="身份证">
          <el-input
            size="small"
            type="text"
            :disabled="actionType === 'update'"
            v-model="createdItem.certNo"
            placeholder="请输入身份证"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone" min-width="120" label="手机号">
          <el-input
            size="small"
            type="text"
            v-model="createdItem.phone"
            placeholder="请输入手机号"
            style="width: 100%;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="validDateEnd" label="到期时间">
          <el-date-picker
            v-model="createdItem.validDateEnd"
            type="date"
            placeholder="请选择到期日期"
            size="small"
            :clearable="false"
            value-format="yyyy-MM-dd"
            style="width: 100%;"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="typeId" label="名单类型">
          <el-select
            size="small"
            v-model="createdItem.typeId"
            clearable
            placeholder="请选择名单类型"
            style="width: 100%;"
          >
            <el-option
              v-for="(item, key) in typeId"
              :key="key"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="formVisible = false">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="formSubmiting"
          @click="save"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 批量导入弹框 -->
    <el-dialog
      title="名单导入"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :visible.sync="upload"
      class="new-dialog"
      width="476px"
    >
      <el-form
        ref="uploadForms"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="100px"
      >
        <el-form-item prop="uploadtypeId" label="名单类型:">
          <el-select
            size="small"
            v-model="uploadForm.uploadtypeId"
            clearable
            placeholder="请选择"
            class="filter-item"
            style="width: 200px;"
          >
            <el-option
              v-for="(item, key) in typeId"
              :key="key"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名单文件:">
          <el-upload
            ref="upload"
            :action="uploadURL"
            :multiple="false"
            :file-list="fileList"
            :accept="fileTypes"
            :data="{ typeId: uploadForm.uploadtypeId }"
            :auto-upload="false"
            :on-success="uploadSuccess"
            :on-change="uploadChange"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <el-button slot="trigger" size="mini">
              <i class="el-icon-upload2"></i>
              上传文件
            </el-button>
            <div class="el-upload__tip" style="margin-top: 0px;" slot="tip">
              支持扩展名: .xls、.xlsx, 点击下载
              <el-button @click="download" type="text" size="mini">
                示例文件
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="rosterUpload('false')">取消</el-button>
        <el-button size="mini" type="primary" @click="submitUpload">
          导入
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  roserList,
  add,
  update,
  uploadURL,
  downloadURL,
  upload
} from '@/api/risksystem/roster/listRoster'
import { Upload } from 'element-ui'
import { list } from '@/api/risksystem/roster/listType'

const defaultPage = {
  limit: 10,
  page: 1
}
const defaultQuery = {
  name: '',
  certNo: '',
  phone: '',
  status: '',
  typeId: '',
  validDateStart: '',
  validDateEnd: '',
  sort: 'id,desc'
}

export default {
  name: 'listRoster',
  components: {
    // TitleContainer
  },
  data() {
    return {
      statusArr: {
        1: '有效',
        2: '无效'
      },
      tableQuery: Object.assign({}, defaultQuery, defaultPage),
      total: 0,
      tableData: [],
      tableHeight: null,
      typeId: [],
      tableLoading: true,

      createdItem: Object.assign({}, defaultQuery),
      rules: {
        typeId: [
          { required: true, message: '请选择名单类型', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        certNo: [
          { required: true, message: '请填写身份证', trigger: 'blur' },
          { validator: this.idCardReg, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          { validator: this.phoneReg, trigger: 'blur' }
        ],
        validDateEnd: [
          { required: true, message: '请选择到期时间', trigger: 'blur' }
        ]
      },
      uploadRules: {
        uploadtypeId: [
          { required: true, message: '请选择名单类型', trigger: 'change' }
        ]
      },
      actionType: '',
      formVisible: false,
      formSubmiting: false,
      upload: false,
      fileTypes: '.xls,.xlsx', //上传文件类型
      fileList: [],
      uploadForm: {
        uploadtypeId: ''
      },
      title: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24
        }
      },
      // 文件上传
      get uploadURL() {
        return uploadURL
      },
      // 文件下载
      get downloadURL() {
        return downloadURL
      }
    }
  },
  computed: {},
  watch: {},
  mounted() {
    this.getList()
    list().then(response => {
      this.typeId = response.data.rows
    })
    this.init()
  },
  beforeDestroy() {
    // 摧毁监听事件
    window.onresize = null
  },
  methods: {
    // 表格高度
    init() {
      var _this = this
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - this.$refs.searchDiv.offsetHeight - 230
      })
      window.onresize = () => {
        this.$nextTick(() => {
          this.tableHeight =
            window.innerHeight - this.$refs.searchDiv.offsetHeight - 230
        })
      }
    },
    getList() {
      this.tableLoading = true
      roserList({
        search: this.tableQuery
      })
        .then(response => {
          this.total = +response.data.count
          this.tableData = response.data.rows
          this.tableLoading = false
        })
        .catch(error => {
          this.tableLoading = false
          this.$message.error(error)
        })
    },
    sortChange(column) {
      if (column.prop === 'createdAt') {
        if (column.order === 'descending') {
          this.tableQuery.sort = 'created_at,desc'
        } else {
          this.tableQuery.sort = 'created_at,asc'
        }
      } else if (column.prop === 'updatedAt') {
        if (column.order === 'descending') {
          this.tableQuery.sort = 'updated_at,desc'
        } else {
          this.tableQuery.sort = 'updated_at,asc'
        }
      }
      this.getList()
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.tableQuery = Object.assign({}, defaultQuery)
      this.getList()
    },
    handleSizeChange(val) {
      this.tableQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.tableQuery.page = val
      this.getList()
    },

    // 新增|编辑
    handlePop(action, data = {}) {
      this.actionType = action
      if (action === 'add') {
        this.title = '添加'
        this.createdItem = Object.assign({}, defaultQuery)
        this.createdItem.validDateStart = this.formatDate(new Date())
      }
      if (action === 'update') {
        this.title = '编辑'
        this.createdItem = Object.assign(this.createdItem, data)
        this.createdItem.typeId = this.createdItem.type.id
        // this.createdItem.name = this.nameEncryption(this.createdItem.name)
        // this.createdItem.certNo = this.createdItem.certNo
        // .substring(0, 6) +
        // '********' +
        // this.createdItem.certNo.substring(
        //   this.createdItem.certNo.length - 4,
        //   this.createdItem.certNo.length
        // )
      }
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs['featureForm'].clearValidate()
      })
    },
    // 姓名加密
    nameEncryption(name) {
      var arr = name.split('')
      for (let i = 0; i < arr.length; i++) {
        if (i > 0) {
          arr[i] = '*'
        }
      }
      return arr.join('')
    },
    idCardReg(rule, value, callback) {
      let cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (cardReg.test(value) === false) {
        callback(new Error('身份证格式错误'))
      } else {
        callback()
      }
    },
    phoneReg(rule, value, callback) {
      let cardReg = /^[1][3,4,5,7,8][0-9]{9}$/
      if (cardReg.test(value) === false) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    },
    // 保存
    save() {
      this.$refs['featureForm'].validate(valid => {
        if (valid) {
          let action = this.actionType
          let data = {}
          if (action === 'add') {
            for (let i in defaultQuery) {
              data[i] = this.createdItem[i]
            }
            add(data).then(response => {
              if (response.code === 0) {
                this.formVisible = false
                this.$message.success('添加成功')
                this.getList()
              }
            })
          } else {
            data.name = this.createdItem.name
            data.certNo = this.createdItem.certNo
            data.phone = this.createdItem.phone
            data.status = this.createdItem.status
            data.phone = this.createdItem.phone
            data.validDateStart = this.createdItem.validDateStart
            data.validDateEnd = this.createdItem.validDateEnd
            data.typeId = this.createdItem.typeId
            data.id = this.createdItem.id
            update(data).then(response => {
              if (response.code === 0) {
                this.formVisible = false
                this.$message.success('修改成功')
                this.getList()
              }
            })
          }
        }
      })
    },
    formatDate(now) {
      var year = now.getFullYear() //取得4位数的年份
      var month = now.getMonth() + 1 //取得日期中的月份，其中0表示1月，11表示12月
      var date = now.getDate() //返回日期月份中的天数（1到31）
      var hour = now.getHours() //返回日期中的小时数（0到23）
      var minute = now.getMinutes() //返回日期中的分钟数（0到59）
      var second = now.getSeconds() //返回日期中的秒数（0到59）
      return (
        year +
        '-' +
        (month < 10 ? '0' + month : month) +
        '-' +
        (date < 10 ? '0' + date : date)
        // (hour < 10 ? '0' + hour : hour) +
        // ':' +
        // (minute < 10 ? '0' + minute : minute) +
        // ':' +
        // (second < 10 ? '0' + second : second)
      )
    },
    download() {
      window.location.href = this.downloadURL
    },
    // 上传
    rosterUpload(val) {
      this.upload = val === 'true' ? true : false
      this.$nextTick(() => {
        this.$refs.uploadForms.clearValidate()
        this.$refs.upload.clearFiles()
      })
    },
    submitUpload() {
      this.$refs['uploadForms'].validate(valid => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.error('请选择上传文件！')
          }
          this.$refs.upload.submit()
        }
      })
    },
    handlePreview(file) {
      // console.log(file)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.fileList = fileList
    },
    uploadChange(file, fileList) {
      console.log(fileList)
      this.fileList = [fileList[fileList.length - 1]]
    },
    beforeUpload(file) {
      if (this.uploadForm.uploadtypeId === '') {
        return false
      }
      this.files = file
      this.fileName = file.name
    },
    uploadSuccess(res) {
      if (res.code === 0) {
        this.$message.success('上传成功！')
        this.upload = false
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    }
  }
}
</script>
<style scoped>
.white-list {
  padding: 20px;
}
</style>
